<template>
  <div class="payment-view">
    <van-nav-bar
      title="订单支付"
      left-arrow
      @click-left="onClickLeft"
    />

    <!-- 支付金额 -->
    <div class="payment-amount">
      <div class="amount-label">支付金额</div>
      <div class="amount-value">
        <span class="currency">¥</span>
        <span class="number">{{ order?.amount || '0.00' }}</span>
      </div>
    </div>

    <!-- 订单信息 -->
    <van-cell-group inset class="order-info">
      <van-cell title="订单编号" :value="order?.orderNo" />
      <van-cell title="商品名称" :value="order?.title" />
      <van-cell title="支付方式" :value="getPaymentMethodText(order?.paymentMethod)" />
    </van-cell-group>

    <!-- 支付二维码 -->
    <div class="qr-code-section" v-if="qrCode">
      <div class="qr-code-wrapper">
        <van-image
          :src="qrCode"
          width="200"
          height="200"
        />
      </div>
      <p class="qr-code-tip">请使用{{ getPaymentMethodText(order?.paymentMethod) }}扫码支付</p>
    </div>

    <!-- 倒计时 -->
    <div class="countdown">
      <van-count-down :time="timeLeft" format="支付剩余时间 mm:ss" />
    </div>

    <!-- 底部按钮 -->
    <div class="bottom-buttons">
      <van-button plain hairline type="primary" block @click="onCancel">取消支付</van-button>
      <van-button type="primary" block @click="checkPaymentStatus">已完成支付</van-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showDialog } from 'vant'

const route = useRoute()
const router = useRouter()

// 订单信息
const order = ref(null)
// 支付二维码
const qrCode = ref('')
// 支付剩余时间（15分钟）
const timeLeft = ref(15 * 60 * 1000)
// 轮询定时器
let pollTimer = null

// 获取订单信息
const fetchOrderInfo = async () => {
  try {
    // TODO: 从后端获取订单信息
    order.value = {
      orderNo: 'ORDER' + Date.now(),
      title: '示例课程',
      amount: 99.99,
      paymentMethod: 'wechat'
    }
    // 生成支付二维码
    generateQRCode()
  } catch (error) {
    showToast('获取订单信息失败')
    console.error(error)
  }
}

// 生成支付二维码
const generateQRCode = async () => {
  try {
    // TODO: 从后端获取支付二维码
    qrCode.value = 'https://img.yzcdn.cn/vant/qrcode.png'
  } catch (error) {
    showToast('生成支付二维码失败')
    console.error(error)
  }
}

// 获取支付方式文本
const getPaymentMethodText = (method) => {
  const methodMap = {
    wechat: '微信支付',
    alipay: '支付宝'
  }
  return methodMap[method] || '未知支付方式'
}

// 检查支付状态
const checkPaymentStatus = async () => {
  try {
    // TODO: 检查支付状态
    showToast('支付成功')
    // 跳转到订单详情或课程页面
    router.replace('/orders')
  } catch (error) {
    showToast('支付状态查询失败')
    console.error(error)
  }
}

// 取消支付
const onCancel = () => {
  showDialog({
    title: '确认取消',
    message: '是否确认取消支付？',
    showCancelButton: true
  }).then(() => {
    router.back()
  })
}

// 开始轮询支付状态
const startPolling = () => {
  pollTimer = setInterval(async () => {
    // TODO: 检查支付状态
    console.log('checking payment status...')
  }, 3000)
}

const onClickLeft = () => {
  showDialog({
    title: '确认离开',
    message: '订单尚未支付，是否确认离开？',
    showCancelButton: true
  }).then(() => {
    router.back()
  })
}

onMounted(() => {
  const orderId = route.params.orderId
  if (orderId) {
    fetchOrderInfo()
    startPolling()
  } else {
    showToast('缺少订单信息')
    router.back()
  }
})

onBeforeUnmount(() => {
  if (pollTimer) {
    clearInterval(pollTimer)
  }
})
</script>

<style lang="scss" scoped>
.payment-view {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 100px;

  .payment-amount {
    margin: 20px 16px;
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    text-align: center;

    .amount-label {
      font-size: 14px;
      color: #969799;
      margin-bottom: 8px;
    }

    .amount-value {
      .currency {
        font-size: 20px;
        color: #ee0a24;
      }

      .number {
        font-size: 32px;
        font-weight: 500;
        color: #ee0a24;
      }
    }
  }

  .order-info {
    margin: 12px 16px;
  }

  .qr-code-section {
    margin: 24px 16px;
    text-align: center;

    .qr-code-wrapper {
      background-color: #fff;
      padding: 20px;
      border-radius: 8px;
      display: inline-block;
    }

    .qr-code-tip {
      margin-top: 12px;
      font-size: 14px;
      color: #969799;
    }
  }

  .countdown {
    text-align: center;
    margin: 16px 0;
    color: #969799;
  }

  .bottom-buttons {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 16px;
    background-color: #fff;
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  }
}
</style>
